package com.yeskery.nut.extend.mcp.server.method;

import com.yeskery.nut.bean.ApplicationContext;
import com.yeskery.nut.extend.mcp.core.JsonMessage;
import com.yeskery.nut.extend.mcp.core.JsonRequest;
import com.yeskery.nut.extend.mcp.core.JsonResponse;
import com.yeskery.nut.extend.mcp.core.schema.PaginationSchema;
import com.yeskery.nut.extend.mcp.server.McpServerCapability;
import com.yeskery.nut.extend.mcp.server.McpServerSession;
import com.yeskery.nut.util.StringUtils;

import java.util.Optional;

/**
 * 基础列表方法处理器
 * @author sprout
 * 2025-04-17 15:20
 */
public abstract class BaseListMethodHandler extends BaseServerMethodHandler {
    /**
     * 构造列表方法处理器
     * @param applicationContext  应用上下文
     * @param mcpServerCapability 服务能力
     */
    public BaseListMethodHandler(ApplicationContext applicationContext, McpServerCapability mcpServerCapability) {
        super(applicationContext, mcpServerCapability);
    }

    @Override
    protected void handleJsonResponse(McpServerSession serverSession, JsonMessage jsonMessage, JsonResponse jsonResponse) {
        JsonRequest jsonRequest = (JsonRequest) jsonMessage;
        PaginationSchema.ListRequest request = jsonRequest.getParams() == null
                ? null : converFromObject(jsonRequest.getParams(), PaginationSchema.ListRequest.class);
        String cursor = Optional.ofNullable(request).map(PaginationSchema.ListRequest::getCursor).orElse(null);
        jsonResponse.setResult(getHandleResult(cursor));
    }

    /**
     * 获取处理结果
     * @param cursor 游标
     * @return 处理结果
     */
    protected abstract Object getHandleResult(String cursor);

    /**
     * 解析数字游标
     * @param cursor 游标
     * @return 数字游标
     */
    protected Integer parseNumberCursor(String cursor) {
        int num = 0;
        if (!StringUtils.isEmpty(cursor)) {
            num = Integer.parseInt(cursor);
        }
        return num;
    }
}
